<template>
  <div>
    <el-form :model="form" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>

  </div>
</template>

<script>
import { ref } from 'vue';
import { useStore } from 'vuex';
import axios from 'axios';
import { useRouter } from 'vue-router'


export default {
  setup() {
    const form = ref({
      username: '',
      password: ''
    });
    const router = useRouter();
    const store = useStore();
    const user = store.state.user;

    const login = async () => {
      try {
        const response = await axios.post('/api/login', form.value);
        if (response.data.code === 200) {
          store.dispatch('login', response.data.data.token);
          ElMessage.success('登录成功');
          router.push(
            {
              name: 'Home'
            }
          )
        } else {
          ElMessage.error(response.data.message);
        }
      } catch (error) {
        ElMessage.error('网络错误');
      }
    };

    return {
      form,
      login,
      user
    };
  }
};
</script>